package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.merchant.api.StoreService;
import com.huiminpay.merchant.convert.StoreConvert;
import com.huiminpay.merchant.dto.StoreDTO;
import com.huiminpay.merchant.entity.Store;
import com.huiminpay.merchant.mapper.StoreMapper;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: StoreServiceImpl
 * @Package: com.huiminpay.merchant.service
 * @Description:
 * @Author 谢同学
 * @Create 2023/11/27 15:22
 * @Version 1.0
 */
@Service
public class StoreServiceImpl implements StoreService {

    @Resource
    StoreMapper storeMapper;

    /**
     * 分页条件查询商户下门店
     * @param storeDTO 商店信息
     * @param pageNo 当前页
     * @param pageSize 分页数量
     * @return
     */
    @Override
    public PageVO<StoreDTO> queryStoreByPage(StoreDTO storeDTO, Integer pageNo, Integer pageSize) {
        //检验数据
        if (storeDTO == null || storeDTO.getMerchantId() == null) {
            throw new BusinessException(CommonErrorCode.E_300009);
        }
        //构建分页条件
        Page<Store> page = new Page<>(pageNo,pageSize);

        //查询数据
        IPage<Store> iPage = storeMapper.selectPage(page, new LambdaQueryWrapper<Store>()
                .eq(Store::getMerchantId, storeDTO.getMerchantId()));
        //获取结果集
        List<Store> stores = iPage.getRecords();
        //entity转 dto
        List<StoreDTO> storeDTOS = StoreConvert.INSTANCE.listentity2dto(stores);

        //封装结果集
        return new PageVO<>(storeDTOS, iPage.getTotal(), pageNo, pageSize);

    }

    /**
     * 新增门店
     * @param storeDTO 门店信息
     * @throws BusinessException
     */
    @Override
    public void addStore(StoreDTO storeDTO) throws BusinessException {

        storeMapper.insert(StoreConvert.INSTANCE.dto2entity(storeDTO));
    }

    /**
     * 查询门店是否属于该商户
     *
     * @param storeId
     * @param merchantId
     * @return
     * @throws BusinessException
     */
    @Override
    public boolean queryStoreInMerchantId(Long storeId, Long merchantId) throws BusinessException {
        return storeMapper.selectCount(new LambdaQueryWrapper<Store>().eq(Store::getId,storeId).eq(Store::getMerchantId,merchantId))>0;
    }
}
